<?php


namespace app\admin\services;


use app\admin\exception\InvalidArgumentException;
use app\admin\exception\ModelNotFoundException;
use app\common\facades\auth\Auth;
use app\common\models\Admin;
use app\Request;

class AuthService
{
    private $adminModel;

    public function __construct(Admin $adminModel)
    {
        $this->adminModel = $adminModel;
    }

    public function login(Request $request)
    {
        $username = $request->post('username', '');
        $password = $request->post('password', '');
        $admin = $this->adminModel->where('username', '=', $username)->find();
        if (!$admin){
            throw new ModelNotFoundException('不存在该用户名');
        }
        if (md5(md5($password)) != $admin->password){
            throw new InvalidArgumentException('密码错误');
        }
        $token = Auth::guard('admin')->login($admin);
        return ['token' => 'Bearer ' . $token];
    }

    public function logout()
    {
        return Auth::guard('admin')->logout();
    }

    public function me()
    {
        return Auth::guard('admin')->user();
    }
}
